# import sys

# sys.path.append("./")
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

# from pywinauto.keyboard import send_keys as SKS
# from window import find_window_by_class, get_window_rect
import win32gui, win32con, win32api
import os, time, json

# from PySide6.QtCore import Signal

"""
    查看浏览器版本: edge://version/
    西在驱动: https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/?form=MA13LH
    driver.find_element(By.XPATH, '//button[text()="Some text"]')
    driver.find_elements(By.XPATH, '//button')
    ID = "id"
    XPATH = "xpath"
    LINK_TEXT = "链接文本"
    PARTIAL_LINK_TEXT = "链接文本包含"
    NAME = "name"
    TAG_NAME = "tag name"
    CLASS_NAME = "class name"
    CSS_SELECTOR = "css selector"
"""


def loadLocalFile(path):
    """加载本地文件"""
    class_name = "#32770"  # 请替换成实际的窗口类名
    window_handle = win32gui.FindWindow(class_name, r"打开")
    child_handle = win32gui.FindWindowEx(window_handle, None, "ComboBoxEx32", None)
    child_handle = win32gui.FindWindowEx(child_handle, None, "ComboBox", None)
    child_handle = win32gui.FindWindowEx(child_handle, None, "Edit", None)
    child_button = win32gui.FindWindowEx(window_handle, None, "Button", r"打开(&O)")
    # 录入数据
    for ch in path:
        win32gui.SendMessage(child_handle, win32con.WM_CHAR, ord(ch), 0)
        time.sleep(0.05)
    # 点击打开按钮
    position = win32api.MAKELONG(5, 5)  # x,y为点击点相对于该窗口的坐标
    win32api.SendMessage(
        child_button, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, position
    )  # 向窗口发送模拟鼠标点击
    time.sleep(0.05)
    win32api.SendMessage(
        child_button, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, position
    )  # 模拟释放鼠标左键


class devel_hedra:
    host = "https://www.hedra.com"
    index = "/app/characters"

    # user = ["3361098@qq.com", "Tanwei99@"]
    # sinout = Signal(str, str)

    def __init__(self, conf={}):
        self.user = conf

    def open(self):
        """初始化"""
        self.browser = webdriver.Edge()
        # self.browser.maximize_window()

    def url(self, url, timer, feb, value):
        self.browser.get(url)
        try:
            # 显式等待
            WebDriverWait(self.browser, timer).until(
                EC.presence_of_element_located((feb, value))
            )
        except BaseException as err:
            print("page is bady.")
            return False
        else:
            print("page is ready.")
            return True

    def close(self):
        self.browser.quit()

    def do_test_console(self):
        """测试控制台"""
        index = self.go_index()
        print("index", index)

    def do_main_console(self):
        """控制台"""
        index = self.go_index()
        print("index", index)
        # self.sinout.emit("info", "加载首页完成.")
        if index:
            login = self.go_login()
            print("login", login)
            # self.sinout.emit("info", "用户登录首页完成.")
        print(self.browser.current_url)
        index = self.url(
            self.host + self.index,
            10,
            By.ID,
            "audio",
        )
        print("Ready", index)
        # self.sinout.emit("info", "用户工作台.")

    def go_index(self):
        """访问首页"""
        index = self.url(self.host + self.index, 10, By.LINK_TEXT, "Sign in to use")
        return index

    def go_login(self):
        """用户登录"""
        login = self.url(self.host + "/login?ref=from", 10, By.XPATH, "//form[1]")
        if not login:
            return False

        email = self.browser.find_element(By.XPATH, "//form[1]/input[1]")
        email.clear()
        email.send_keys(self.user["usermail"])
        paswd = self.browser.find_element(By.XPATH, "//form[1]/input[2]")
        paswd.clear()
        paswd.send_keys(self.user["password"])
        submit = self.browser.find_element(By.XPATH, "//form[1]/button[1]")
        submit.click()

        try:
            # 显式等待
            WebDriverWait(self.browser, 60).until(
                EC.presence_of_element_located((By.LINK_TEXT, "Try beta"))
            )
        except BaseException as err:
            return False
        else:
            return True

    def uploadRes(self, res):
        """上传资料"""

        # 准备资料
        ap = os.path.abspath(res[1])
        ip = os.path.abspath(res[0])
        print(ap, ip)

        # 检查浏览器刷新页面
        self.url(
            self.host + self.index,
            30,
            By.XPATH,
            '//div[@data-testid="import-audio-button"]',
        )
        time.sleep(3)
        self.browser.find_element(
            By.XPATH, '//div[@data-testid="import-audio-button"]'
        ).click()

        # 移除旧音频
        try:
            WebDriverWait(self.browser, 10).until(
                EC.presence_of_element_located(
                    (By.XPATH, '//div[@data-testid="audio-clip-container"]')
                )
            )
        except BaseException as err:
            print("debug: 没有旧音频,继续进度...")
        else:
            self.browser.find_element(
                By.XPATH, '//button[@data-testid="remove-audio-clip"]'
            ).click()

        # 传音频
        try:
            # 选择上传文件
            self.browser.find_element(
                By.XPATH, '//div[@data-testid="audio-dropzone"]'
            ).click()
            # self.browser.find_element(
            #     By.XPATH, '//input[@accept="audio/mpeg, audio/wav"]/..'
            # ).click()
            time.sleep(3)
            loadLocalFile(ap)
            WebDriverWait(self.browser, 120).until(
                EC.presence_of_element_located(
                    (By.XPATH, '//div[@data-testid="audio-clip-container"]')
                )
            )
        except BaseException as err:
            print("err: 上传音频失败")
            return False
        print("info: 上传音频成功")

        # 检查旧图像
        try:
            WebDriverWait(self.browser, 5).until(
                EC.presence_of_element_located(
                    (By.XPATH, '//img[@data-testid="avatar-image"]')
                )
            )
        except BaseException as err:
            print("debug: 没有旧图像,继续进度...")

        # 传图像 data-testid="avatar-canvas-container"
        try:
            self.browser.find_element(
                By.XPATH, '//input[@accept="image/png, image/jpeg, image/webp"]/..'
            ).click()
            time.sleep(3)
            loadLocalFile(ip)
            WebDriverWait(self.browser, 60).until(
                EC.presence_of_element_located(
                    (By.XPATH, '//img[@data-testid="avatar-image"]')
                )
            )
        except BaseException as err:
            print("err: 上传图像失败")
            return False
        print("info: 上传图像成功")

        # 提交任务
        try:
            # 显式等待 data-testid="generate-button-disabled";data-testid="generate-button-enabled"
            WebDriverWait(self.browser, 60).until(
                EC.presence_of_element_located(
                    (By.XPATH, '//button[@data-testid="generate-button-enabled"]')
                )
            )
        except BaseException as err:
            print("err: 等待生成按钮失败")
            return False
        time.sleep(3)
        self.browser.find_element(
            By.XPATH, '//button[@data-testid="generate-button-enabled"]'
        ).click()
        print("info: 提交任务成功")

        # 等待生成
        try:
            # 显式等待
            WebDriverWait(self.browser, 3600).until(
                EC.presence_of_element_located((By.ID, "primaryVideoElement"))
            )
        except BaseException as err:
            print("err: 等待生成失败")
            return False

        # 获取资源
        video = self.browser.find_element(By.ID, "primaryVideoElement")
        print("视频地址:", video.get_attribute("src"))
        return video.get_attribute("src")
